package com.sugree.twitter.views;

import java.io.IOException;
import java.util.Vector;
import java.util.Enumeration;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.rms.RecordStoreException;

import com.substanceofcode.twitter.model.Status;
import com.substanceofcode.twitter.Settings;
import com.substanceofcode.twitter.TwitterApi;
import com.substanceofcode.utils.Log;
import com.sugree.twitter.TwitterController;

public class SetupScreen extends Form implements CommandListener {
	private TwitterController controller;
	private TwitterApi api;

	private TextField usernameField;
	private TextField passwordField;
	private Command saveCommand;
	private Command cancelCommand;

	public SetupScreen(TwitterController controller, TwitterApi api) {
		super("Setup");
		this.controller = controller;
		this.api = api;

		Settings settings = controller.getSettings();

		String username = settings.getStringProperty(Settings.USERNAME, "");
		usernameField = new TextField("Username", username, 32, TextField.ANY);
		append(usernameField);

		String password = settings.getStringProperty(Settings.PASSWORD, "");
		passwordField = new TextField("Password", password, 32, TextField.PASSWORD);
		append(passwordField);

		saveCommand = new Command("Save", Command.OK, 1);
		addCommand(saveCommand);
		cancelCommand = new Command("Cancel", Command.CANCEL, 2);
		addCommand(cancelCommand);

		setCommandListener(this);
	}

	public void commandAction(Command cmd, Displayable display) {
		if (cmd == saveCommand) {
			String username = usernameField.getString();
			String password = passwordField.getString();

			Settings settings = controller.getSettings();

			settings.setStringProperty(Settings.USERNAME, username);
			settings.setStringProperty(Settings.PASSWORD, password);

			api.setUsername(username);
			api.setPassword(password);

			try {
				settings.save(true);
			} catch (IOException e) {
				Log.error(e.toString());
			} catch (RecordStoreException e) {
				Log.error(e.toString());
			}
			controller.showTimeline();
		} else if (cmd == cancelCommand) {
			controller.showTimeline();
		}
	}
}
